import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.util.Arrays;

public class RouterProtocol {
	
	static boolean debug = false;
	
	public static void sendRouterProtocolPacket( RouterProtocolPacket packet, DatagramSocket socket, SocketAddress address ) throws IOException{
		byte[] bytePacket = packet.toByteArray(); 
		DatagramPacket udpPacket = new DatagramPacket( bytePacket, bytePacket.length, address );
		socket.send( udpPacket );
		if( debug ){
			System.err.println("Sent from "+packet.getIdSender()+ " to "+address );
			System.err.println("	bytePacket= "+ Arrays.toString( bytePacket) +"\r\n"+"	routerPacket= "+ packet+"]");
		}
	}
	
	public static RouterProtocolPacket receivePacket( DatagramSocket socket ) throws IOException{
		byte[] bytePacket = new byte[RouterProtocolPacket.PACKET_LENGTH];
		socket.receive( new DatagramPacket( bytePacket, bytePacket.length ) );
		RouterProtocolPacket packet = new RouterProtocolPacket( bytePacket );
		
		if( debug ){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.err.println("Received socket "+ socket.getLocalPort() + " received from " + packet.getIdSender());
			System.err.println("	bytePacket= "+ Arrays.toString( bytePacket) +"\r\n"+"	routerPacket= "+ packet+"]");
		}
		return packet;
	}
	


}
